package cn.shoptnt.service.trade.order.impl;

import cn.hutool.core.collection.CollUtil;
import cn.shoptnt.client.member.MemberClient;
import cn.shoptnt.client.promotion.CouponClient;
import cn.shoptnt.model.member.dos.MemberCoupon;
import cn.shoptnt.model.promotion.coupon.vo.GoodsCouponPrice;
import cn.shoptnt.model.trade.order.dto.OrderDTO;
import cn.shoptnt.model.trade.order.vo.TradeVO;
import cn.shoptnt.service.trade.order.PlatformCouponUseManger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gy
 * @version 1.0
 * @sinc 7.x
 * @date 2023年01月04日 11:01
 */
@Service
public class PlatformCouponUseMangerImpl implements PlatformCouponUseManger {

    @Autowired
    private MemberClient memberClient;

    @Autowired
    private CouponClient couponClient;

    @Override
    public void useCoupon(TradeVO tradeVO) {


        List<Long> memberCouponIdList = new ArrayList<>();

        tradeVO.getOrderList().stream()
                //过滤掉没有非平台优惠券的订单
                .filter(OrderDTO::getSiteCoupon)
                .forEach(orderDTO -> {
                    List<GoodsCouponPrice> goodsCouponPrices = orderDTO.getGoodsCouponPrices();
                    if (CollUtil.isNotEmpty(goodsCouponPrices)) {
                        //获取平台优惠券
                        goodsCouponPrices.stream()
                                .map(GoodsCouponPrice::getMemberCouponId)
                                .forEach(memberCouponIdList::add);
                    }
                });


        memberCouponIdList.stream()
                .distinct()
                .forEach(memberCouponId -> {
            //使用优惠券
            this.memberClient.usedCoupon(memberCouponId, tradeVO.getTradeSn());
            //查询该使用了的优惠券
            MemberCoupon memberCoupon = this.memberClient.getModel(tradeVO.getMemberId(), memberCouponId);
            //修改店铺已经使用优惠券数量
            this.couponClient.addUsedNum(memberCoupon.getCouponId());
        });

    }
}
